<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
//引用对应的命名空间
use Gregwar\Captcha\CaptchaBuilder;
use App\Models\Admin;
use Hash;
class LoginController extends Controller
{
    public function getIndex()
    {
        //引入登陆页面
        return view('admin.login.index');
    }

    //登录
    public function postDologin(request $request)
    {
        $code = $request->input('code');
        $res = self::getCode($code);
        if($res==0){
            return back()->with('error','您输入验证码错误');
        }else{
            $aname = $request->input('aname');
            $apassword = $request->input('apassword');
            $data = Admin::where('aname',$aname)->first();
            if($data){
                if($data->astatus){
                    if (Hash::check($apassword, $data->apassword)){
                        session(['data'=>$data]);
                        return redirect('/admin/index')->with('success','登录成功');
                    }else{
                        return back()->with('error','用户名或密码错误');
                    }
                }else{
                     return back()->with('error','您的账号已被禁用');
                }
            }else{
                return back()->with('error','用户名或密码错误');
            }
        }
        
    }

    //注销
    public function getDologout()
    {
        session()->pull('data');
        return redirect('/admin/login')->with('success','注销成功');
    }

    //生成验证码
    public function getCreateverify()
    {
        //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();
        // var_dump($phrase);
        //把内容存入session
        session(['milkcaptcha'=> $phrase]);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }

    //验证码验证
    public static function getCode($code)
    {
        if (session('milkcaptcha') == $code) {
            //用户输入验证码正确
            return 1;
        } else {
            //用户输入验证码错误
            return 0;
        }
    }
}
